//
//  PlaceOrderProductListViewController.m
//  HAODE
//
//  Created by LiYinDi on 16/1/11.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "PlaceOrderProductListViewController.h"
#import "PlaceOrderParentTableViewCell.h"
#import "PlaceOrderSubTableViewCell.h"
#import "HttpRequest.h"
#import "UIImageView+WebCache.h"
#import "PlaceOrderSpecTableViewCell.h"
//#import "LYDPopoverView.h"
#import "LYDPopViewController.h"
#import "PlaceOrderSubDataModel.h"
#import "FMDB.h"
#import "TheLoginViewController.h"
#import "NoSpecFmdbModel.h"
#import "NoSpecFmdbTool.h"

#import "HasSpecFmdbModel.h"
#import "HasSpecFmdbTool.h"
@interface PlaceOrderProductListViewController ()<PlaceOrderSubTableViewDelegate,PlaceOrderSpecCellDelegate,LYDPopViewControllerDelegate>
{
    NSUInteger _PageIndex;
    NSUInteger _TotalCount;
    NSUInteger _TotalPage;
    NSMutableArray *modelArray;
    NSString *itemTypeCodeStr;
    NSInteger subCellTag;
    NSString  *userToken;
    
    LYDPopViewController *popVC;
    
    
}
@property(nonatomic,strong)FMDatabase *db;
@property(nonatomic,strong)FMDatabase *specdb;
@end

@implementation PlaceOrderProductListViewController
-(void)viewWillAppear:(BOOL)animated
{
   
    [self setAutolayout];
    
    [self initSub];
    [self getTotalCountFromDB];
    CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
    CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
    _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
    [_parentTableView reloadData];
    
    NSIndexPath *ip=[NSIndexPath indexPathForRow:0 inSection:0];
    [_parentTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
    itemTypeCodeStr=[[_parentDataArray objectAtIndex:0] objectForKey:@"TypeCode"];
    
    _PageIndex=0;
    [self loadItemNextPage:_PageIndex];
    


  }
- (void)viewDidLoad {
    [super viewDidLoad];
    [_parentTableView setBackgroundColor:[UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0f]];
    
}
-(void)initSub
{
    modelArray=[NSMutableArray array];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
 
    _cornerCountLabel.layer.cornerRadius=10;
    _cornerCountLabel.layer.masksToBounds=YES;
//    [self createFB];
//    [self createSpecFB];
   
}
-(void) loadItemNextPage:(NSUInteger)oldPageNum {
    if(oldPageNum!=0 && _TotalCount<=modelArray.count)
        return;
    if(oldPageNum == 0){
        [modelArray removeAllObjects];
        [_subTableView reloadData];
    }
    _PageIndex=oldPageNum+1;
    [self requestItemList: _PageIndex pageSize:6];
}
-(void)requestItemList:(NSUInteger)pageIndex pageSize:(NSUInteger)pageSize
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    userToken=Token;
    if (Token ==nil) {
        Token=@"dd";
    }
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
    [params setObject:Token forKey:@"tokenId"];
    NSNumber *pageSizeNumber = [NSNumber numberWithInteger:pageSize];
    NSNumber *pageIndexNumber = [NSNumber numberWithInteger:pageIndex];
    [params setObject:pageSizeNumber forKey:@"PageSize"];
    [params setObject:pageIndexNumber forKey:@"PageIndex"];
    
    [params setObject:itemTypeCodeStr forKey:@"itemTypeCode"];
    [params setObject:_ptype forKey:@"ptype"];
    
    [HttpRequest requestData:@"Product/GetProductListO" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
   
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                _TotalCount=[[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue];
                
                if (_TotalCount%6!=0) {
                    _TotalPage=_TotalCount/6+1;
                }
                else if (_TotalCount%6==0)
                {
                    _TotalPage=_TotalCount/6;
                }
                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                for (NSDictionary *dic in mItemsArray) {
                    PlaceOrderSubDataModel *dataModel=[PlaceOrderSubDataModel dataModelWithDict:dic];
                    [modelArray addObject:dataModel];
                    
                }
                [_subTableView reloadData];
                
                
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                //  [Global showTextHud:requestResultStr view:self.view];
                [Global showTextHudSub:requestResultStr view:self.view];
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    if ([self.delegate respondsToSelector:@selector(loginAgain)]) {
                        
                        [self.delegate loginAgain];
                    }

//                     TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
//                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                
            }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==_parentTableView) {
        return _parentDataArray.count;
    }
    else
    {
        return modelArray.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_parentTableView) {
        return 55;
    }
    else
    {
        return 122;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==_parentTableView) {
        
        static NSString * const  ResultTableViewCellIdentifier = @"PlaceOrderParentTableViewCell";
        PlaceOrderParentTableViewCell *cell=( PlaceOrderParentTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ResultTableViewCellIdentifier];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PlaceOrderParentTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        
        //  cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame] ;
        cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        cell.contentLabel.highlightedTextColor=[UIColor blackColor];
//        cell.contentLabel.highlighted=
        
        
        if (_parentDataArray.count>0) {
            cell.contentLabel.text=[[_parentDataArray objectAtIndex:indexPath.row] objectForKey:@"TypeName"];
        }
        
        
        return cell;
    }
    else if(tableView==_subTableView)
    {
        static NSString * const  ResultTableViewCellIdentifier = @"PlaceOrderSubTableViewCell";
        PlaceOrderSubTableViewCell *cell=( PlaceOrderSubTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ResultTableViewCellIdentifier];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PlaceOrderSubTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        cell.delegate=self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.subtractBtn.tag=indexPath.row;
        PlaceOrderSubDataModel *model=modelArray[indexPath.row];
        
        [cell.productImageView setImageWithURL:[NSURL URLWithString:model.imageUrlFull]];
        
        
        [cell.productNameLabel setText:model.itemName];
        
        
            NSString *stockCountStr=[NSString stringWithFormat:@"%d",[model.invQty intValue]];
            
            NSString *str=[NSString stringWithFormat:@"库存 %@",stockCountStr];
            NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
            [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] range:NSMakeRange(3, stockCountStr.length)];
            
            cell.stockCountLabel.attributedText=attriString;

        if ([model.specType intValue]==0) {
              cell.priceLabel.text=[NSString stringWithFormat:@"¥%0.02f",[model.salePrice floatValue] ];
        }
        else
        {
             cell.priceLabel.text=[NSString stringWithFormat:@"¥%0.02f-%0.02f",[model.minPrice floatValue],[model.maxPrice floatValue]];
        }
            
        
            NSString *countStr=[self getSubTableCellCountFromDB:model.itemId tag:indexPath.row];
//         NSLog(@"countStr///===%@",countStr);
            if ([countStr intValue]>0) {
                cell.countLabel.text=countStr;
                cell.countLabel.hidden=NO;
                cell.backGroundLabel.hidden=NO;
                cell.xLabel.hidden=NO;
                
            }
            else
            {
                cell.countLabel.hidden=YES;
                cell.backGroundLabel.hidden=YES;
                cell.xLabel.hidden=YES;
                //                cell.subtractBtn.hidden=YES;
            }
            if ([model.specType intValue]==0&&[countStr intValue]>0) {
                cell.subtractBtn.hidden=NO;
            }
            else
            {
                cell.subtractBtn.hidden=YES;
            }
        
        if (indexPath.row == [modelArray count] - 1)
        {
            if (_PageIndex<=_TotalPage) {
                //  NSLog(@"###LOADING???");
                [self loadItemNextPage:_PageIndex];
            }
        }
        
        
        return cell;
        
    }
    
    return nil;
}
-(void)subtractBtnClick:(NSUInteger)tag
{
    PlaceOrderSubDataModel *model=modelArray[tag];
    subCellTag=tag;
    if ([model.specType intValue]==0) {
        
        NSString *oriCount=[NSString stringWithFormat:@"%d",[model.specCount intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
        
        
        
        if ([oriCount intValue]>0)
        {
            model.specCount=oriCount;
            [modelArray replaceObjectAtIndex:tag withObject:model];
            [self modifyFBCount:tag];
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:0];
            
            _cornerCountLabel.text=[NSString stringWithFormat:@"%d",_cornerCountLabel.text.intValue-1];
            [_subTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
            
            
            
        }
        else if ([oriCount intValue]==0)
        {
            model.specCount=oriCount;
            [modelArray replaceObjectAtIndex:tag withObject:model];
            //            [_db executeUpdate:@"DELETE FROM t_UserPlaceOrder WHERE userToken = ? AND itemId = ? AND typeString = ? ;",userToken,model.itemId,_typeString];
            NSString *sqlStr=[NSString stringWithFormat:@"DELETE FROM t_NoSpec WHERE userToken = '%@' AND itemId = '%@' AND typeString = '%@' ;",userToken,model.itemId,_typeString];
            [HasSpecFmdbTool deleteData:sqlStr];
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:0];
            
            
            _cornerCountLabel.text=[NSString stringWithFormat:@"%d",_cornerCountLabel.text.intValue-1];
            [_subTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
        }
        
    }
    else{
        [self showPopView];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_parentTableView) {
        itemTypeCodeStr=[[_parentDataArray objectAtIndex:indexPath.row] objectForKey:@"TypeCode"];
         [modelArray removeAllObjects];
        _PageIndex=0;
        [self loadItemNextPage:_PageIndex];
    }
    else if (tableView==_subTableView)
    {
        PlaceOrderSubDataModel *model=modelArray[indexPath.row];
        subCellTag=indexPath.row;
        if ([_typeString isEqualToString:@"WhsOut"]||[_typeString isEqualToString:@"PlaceOrder"]) {
            if ([model.specType intValue]==0) {
                
                
                if ([model.specCount intValue]<[model.invQty intValue]) {
                    
                    NSString *oriCount=[NSString stringWithFormat:@"%d",[model.specCount intValue]];
                    oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
                    model.specCount=oriCount;
                    
                    
                    [modelArray replaceObjectAtIndex:indexPath.row withObject:model];
                    [self modifyFBCount:indexPath.row];
                    NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:indexPath.row inSection:0];
                    
                    
                   _cornerCountLabel.text=[NSString stringWithFormat:@"%d",_cornerCountLabel.text.intValue+1];
                    [_subTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
                    
                }
                else
                {
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"库存不足" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                }
                //   [self setUserDefaults];
                // NSLog(@"dict===222==%@",dict);
            }
            else{
                [self showPopView];
                
            }
        }
        else
        {
            if ([model.specType intValue]==0) {
                
                
                NSString *oriCount=[NSString stringWithFormat:@"%d",[model.specCount intValue]];
                oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
                model.specCount=oriCount;
                //                NSLog(@"model.specCountffffff===%@",model.specCount);
                
                [modelArray replaceObjectAtIndex:indexPath.row withObject:model];
                
                [self modifyFBCount:indexPath.row];
                NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:indexPath.row inSection:0];
                [_subTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
                
                _cornerCountLabel.text=[NSString stringWithFormat:@"%d", _cornerCountLabel.text.intValue+1];
            }
            else{
                [self showPopView];
            }
            
        }
   
    }
}
-(void)showPopView
{
    PlaceOrderSubDataModel *model=modelArray[subCellTag];
    popVC=[[LYDPopViewController alloc] init];
    popVC.delegate=self;
    popVC.productURL=model.imageUrlFull;
    popVC.productNameStr=model.itemName;
    popVC.productPriceScopeStr=[NSString stringWithFormat:@"¥%0.02f", [model.salePrice floatValue]];
    popVC.productStockCountStr=[NSString stringWithFormat:@"%d",[model.invQty intValue]];
    popVC.itemIDStr=model.itemId;
    popVC.itemCodeStr=model.itemCode;
    popVC.typeString=_typeString;
    popVC.countStr= model.specCount;
    
    [popVC show];
    
//    NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:subCellTag inSection:0];
//    UITableViewCell *cell = [_subTableView cellForRowAtIndexPath:indexPath1];
//    PlaceOrderSubTableViewCell *subCell=( PlaceOrderSubTableViewCell *)cell;
    
//    NSLog(@"popVC.countStr===%@",popVC.countStr);

}
#pragma mark LYDPopDelegate
-(void)closePop:(NSString *)countStr
{
    
    PlaceOrderSubDataModel *model=modelArray[subCellTag];
    NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:subCellTag inSection:0];
    UITableViewCell *cell = [_subTableView cellForRowAtIndexPath:indexPath1];
    PlaceOrderSubTableViewCell *subCell=( PlaceOrderSubTableViewCell *)cell;
    subCell.countLabel.text=countStr;
    model.specCount=countStr;
    [modelArray replaceObjectAtIndex:subCellTag withObject:model];
    //    NSLog(@"countStr Before=====%@",countStr);
    if ([countStr intValue]>0) {
        //        NSLog(@"countStr After=====%@",countStr);
        [self modifyFBCount:subCellTag];
    }
    else
    {
        //        [_db executeUpdate:@"DELETE FROM t_UserPlaceOrder WHERE userToken = ? AND itemId = ? AND typeString = ? ;",userToken,model.itemId,_typeString];
        NSString *sqlStr=[NSString stringWithFormat:@"DELETE FROM t_NoSpec WHERE userToken = '%@' AND itemId = '%@' AND typeString = '%@' ;",userToken,model.itemId,_typeString];
        [NoSpecFmdbTool deleteData:sqlStr];
    }
    
    
    [self getTotalCountFromDB];
    
    
    CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
    CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
    _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
    //    [self getTotalMoneyFromHasSpecDB];
    
    NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:subCellTag inSection:0];
    [_subTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
}
- (IBAction)confirmSubmitBtnClick:(id)sender {
    
    // [self setUserDefaults];
    //  NSLog(@"placeOrderDataDict===%@",placeOrderDataDict);
    if ([self.delegate respondsToSelector:@selector(confirmSubmit)]) {
        
        [self.delegate confirmSubmit];
    }
    
    
}
- (IBAction)selectedBtnCLICK:(id)sender {
    //  [self setUserDefaults];
    if ([self.delegate respondsToSelector:@selector(selectedGoodsBtnClick)]) {
        
        [self.delegate selectedGoodsBtnClick];
    }
    
}
-(NSString *)getSubTableCellCountFromDB:(NSString *)itemIDStr tag:(NSInteger)tag
{
    PlaceOrderSubDataModel *model=modelArray[tag];
    NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:userToken itemId:itemIDStr itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:_typeString];
    
    NSString *countString=[NoSpecFmdbTool getSubTableCellCount:fmModel ];
    
    model.specCount=countString;
    [modelArray replaceObjectAtIndex:tag withObject:model];
    
    return countString;
    
}

-(void)getTotalCountFromDB
{
    
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:_typeString];
    NSString *resultStr=[NoSpecFmdbTool getCornerCount:model];
    _cornerCountLabel.text=[NSString stringWithFormat:@"%d",resultStr.intValue];
    
}

-(void)modifyFBCount:(NSInteger)tag
{
    PlaceOrderSubDataModel *model=modelArray[tag];
    NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:userToken itemId:model.itemId itemCode:model.itemCode imageUrlFull:model.imageUrlFull itemName:model.itemName maxPrice:model.maxPrice minPrice:model.minPrice salePrice:model.salePrice invQty:model.invQty specType:model.specType specCount:model.specCount typeString:_typeString];
    [NoSpecFmdbTool modifySpecCount:fmModel];
    
}
-(CGFloat)getTotalMoneyFromNoSpecDB
{
    CGFloat totalNoSpecMoney=0;
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:_typeString];
    NSString *resultStr=[NoSpecFmdbTool getTotalNoSpecMoney:model];
    totalNoSpecMoney=resultStr.floatValue;
    return totalNoSpecMoney;
}
-(CGFloat)getTotalMoneyFromHasSpecDB
{
    CGFloat totalHasSpecMoney=0;
    HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" colorSpecID:@"" sizeSpecID:@"" specName:@"" specPrice:@"" specStock:@"" specCount:@"" typeString:_typeString specID:@""];
    NSString *resultStr=[HasSpecFmdbTool getTotalSpecMoney:model];
    totalHasSpecMoney=[resultStr floatValue];
    
    return totalHasSpecMoney;
    
}


 -(void)setAutolayout
{
    [_parentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.width.equalTo(@85) ;
        make.top.equalTo(@64) ;
        make.bottom.equalTo(self.view.mas_bottom ).with.offset(-48);
    }];
    [_subTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_parentTableView.mas_right) ;
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(@64) ;
        make.bottom.equalTo(self.view.mas_bottom ).with.offset(-48);
    }];
    [_totalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_totalCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    
    
}


@end
